package interview.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhangrongqing
 * @Date: 2019/11/28 15:29
 */
public class ProducerAndConsumer2 {
    private int count = 10;

    public void consumer() throws InterruptedException {
        synchronized (this) {
            System.out.println("等待消费");
            System.out.println("消费者消费1个，剩余" + --count);
            this.wait();//wait方法解锁等待
        }
    }

    public void producer() throws InterruptedException {
        synchronized (this) {
            System.out.println("开始生产了");
            Thread.sleep(1000);
            count++;
            this.notify();    //notifyAll通知所有wait的线程开始工作
        }
    }


    public static void main(String[] args) {
        ProducerAndConsumer2 pcTest = new ProducerAndConsumer2();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(() -> {
            try {
                pcTest.consumer();
            } catch (InterruptedException e) {
            }
        });
        executor.execute(() -> {
            try {
                pcTest.producer();
            } catch (InterruptedException e) {
            }
        });
        executor.shutdown();
    }
}
